package top.abilities.util.utils;


import com.alibaba.fastjson.JSON;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import top.abilities.util.enums.MessageEnum;
import top.abilities.util.util.Jsons;
import top.abilities.util.util.ParseMD5;
import top.abilities.util.util.httpClient.SimpleHttpUtils;
import top.abilities.util.utils.spring.SpringUtils;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.*;

/**
 * 获取i18n资源文件
 *
 */
@Component
public class MessageUtils
{
    private static Logger _log = LoggerFactory.getLogger(MessageUtils.class);
    @Autowired
    private Environment env;
    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    private static Environment staticEnv;
    private static ThreadPoolTaskExecutor staticThreadPoolTaskExecutor;

    @PostConstruct
    public void initEnv(){
        staticEnv=env;
        staticThreadPoolTaskExecutor=threadPoolTaskExecutor;
    }
    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     * @return
     */
    public static String message(String code, Object... args)
    {
        MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
        return messageSource.getMessage(code, args, null);
    }

    /**
     * 推送公众号信息
     * @param fesid 员工id
     * @param map 信息内容，见模板
     * @param messageEnum 模板ID MessageEnum枚举
     * @return
     */
    public static String sendMessage(Integer fesid,Map map, MessageEnum messageEnum) {
        String url=staticEnv.getProperty("gap.message.api.url");
        String appaccount=staticEnv.getProperty("gap.message.api.appaccount");
        String appSecret=staticEnv.getProperty("gap.message.api.appSecret");

//        String url = "http://testapi.feser.com.cn/API/Message/SendTempMessage";
//        String appaccount = "renren";
//        String appSecret = "okh77osnw3df20cv9c9r00ed95yy5437";

        Map paramMap = new LinkedHashMap();
        paramMap.put("TempId", messageEnum.getUniqueKey());
        paramMap.put("Fesid", fesid);
        paramMap.put("Data", map);
        String uuid = UUID.randomUUID().toString();
        long timespan = System.currentTimeMillis() / 1000;
        Map extendMap = new LinkedHashMap();
        extendMap.put("appaccount", appaccount);
        extendMap.put("noncestr", uuid);
        extendMap.put("timestamp", String.valueOf(timespan));
        String signStr = signString(paramMap, extendMap);
        //获取MD5加密后的字符串
        String sign = ParseMD5.parseStrToMd5U32(appSecret + signStr).toLowerCase();
        Map lastMap = new LinkedHashMap();
        lastMap.put("appaccount", appaccount);
        lastMap.put("noncestr", uuid);
        lastMap.put("jsonParam", paramMap);
        lastMap.put("timestamp", String.valueOf(timespan));
        lastMap.put("sign", sign);
        staticThreadPoolTaskExecutor.execute(() -> {
            try {
                String param = Jsons.objToJson(lastMap);
                _log.info("请求url：" + url);
                _log.info("公总号信息推送入参：" + param);
                String Re = SimpleHttpUtils.doPostJson(url, param);
                _log.info("公总号信息推送出参：" + Re);
            } catch (IOException e) {
                e.printStackTrace();
                _log.info("公总号信息推送错误：" + e.getMessage());
            }
        });
        return "";
    }

    public static String signString(Map paramMap,Map extendMap){
        TreeMap<String,Object> treeMapResult = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.toLowerCase().compareTo(o2.toLowerCase());
            }
        });
        Iterator<Map.Entry<String, Object>> entryIterator = paramMap.entrySet().iterator();
        while (entryIterator.hasNext()) {
            Map.Entry<String, Object> entry = entryIterator.next();
            if(entry.getValue() instanceof Map){
//                treeMapResult.put(entry.getKey(), JSON.toJSONString(entry.getValue()));
            }
            else {
                treeMapResult.put(entry.getKey(), entry.getValue());
            }
        }
        treeMapResult.putAll(extendMap);
        //遍历treeMap，将参数值进行拼接
        StringBuilder stringBuilder = new StringBuilder();
        Iterator<String> it = treeMapResult.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            stringBuilder.append(key);
            stringBuilder.append(treeMapResult.get(key));
        }
        return  stringBuilder.toString();
    }

    public static void main(String[] args) {
        Map map=new HashMap();
        Map map1=new HashMap();
        map1.put("value","您的账户积分有变动");
        map1.put("color","#173177");
        Map map3=new HashMap();
        map3.put("value","增加积分");
        map3.put("color","#173177");
        Map map4=new HashMap();
        map4.put("value","100");
        map4.put("color","#173177");
        Map map5=new HashMap();
        map5.put("value","500");
        map5.put("color","#173177");
        Map map2=new HashMap();
        map2.put("value","参加抽奖获得积分奖励");
        map2.put("color","#173177");
        map.put("first",map1);
        map.put("keyword1",map3);
        map.put("keyword2",map4);
        map.put("keyword3",map5);
        map.put("remark",map2);
        MessageUtils.sendMessage(1,map, MessageEnum.successful_recharge_reminder);
    }
}
